/**
 * 分类模型
 * 用于对书签进行分类管理
 */

const mongoose = require('mongoose');

// 定义分类模式
const CategorySchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, '请提供分类名称'],
    trim: true,
    maxlength: [50, '分类名称不能超过50个字符']
  },
  description: {
    type: String,
    maxlength: [500, '描述不能超过500个字符']
  },
  icon: {
    type: String, // 存储图标的类名或URL
    default: 'folder'
  },
  color: {
    type: String, // 存储颜色代码
    default: '#409EFF'
  },
  order: {
    type: Number, // 用于排序
    default: 0
  },
  parent: {
    type: mongoose.Schema.ObjectId,
    ref: 'Category',
    default: null // 顶级分类的父级为null
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
}, {
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// 虚拟字段：子分类
CategorySchema.virtual('children', {
  ref: 'Category',
  localField: '_id',
  foreignField: 'parent',
  justOne: false
});

// 虚拟字段：书签数量
CategorySchema.virtual('bookmarkCount', {
  ref: 'Bookmark',
  localField: '_id',
  foreignField: 'category',
  count: true
});

// 删除分类前，将其子分类的parent设为null
CategorySchema.pre('remove', async function(next) {
  await this.model('Category').updateMany(
    { parent: this._id },
    { parent: null }
  );
  next();
});

module.exports = mongoose.model('Category', CategorySchema); 